import axios from 'axios'
import store from '@/store'
import router from '@/router'

const instance = axios.create({
  baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net',
  timeout: 5000
})

// 添加请求拦截器
instance.interceptors.request.use(
  function (config) {
    // 在发送请求之前做些什么
    const token = store.state.user.profile.token
    if (token) {
      config.headers.Authorization = `Bearer${token}`
    }
    return config
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error)
  }
)

// 添加响应拦截器
instance.interceptors.response.use(
  function (response) {
    const res = response.data
    return res
  },
  function (error) {
    // 对响应错误做点什么
    if (error.response.status === 401) {
      store.commit('user/setUser', {})
      router.push(
        `/login?return_url${encodeURIComponent(
          router.currentRoute.value.fullPath
        )}`
      )
      // console.log(router.push)
    }
    return Promise.reject(error)
  }
)
export default instance
